<html lang="en">
	<head>
		<title>Yuka | Navmesh with Spatial Index and Tasks</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link rel="stylesheet" type="text/css" href="../../lib/styles.css">
		<link rel="shortcut icon" type="image/x-icon" href="https://mugen87.github.io/yuka/favicon.ico">
	</head>
<body>

	<section id="loading-screen">
		<div class="spinner">
			<div class="rect1"></div>
			<div class="rect2"></div>
			<div class="rect3"></div>
			<div class="rect4"></div>
			<div class="rect5"></div>
		</div>
	</section>

	<section id="info">
		<p>
			Navigation Mesh with Spatial Index and Tasks <br/>
			Active Game Entities: <span id="entityCount"></span><br/>
			Convex Regions of NavMesh: <span id="regionCount"></span><br/>
			Partitions of Spatial Index: <span id="partitionCount"></span><br/>
		</p>
	</section>

	<script type="module">

		import * as YUKA from '../../../build/yuka.module.js';
		import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.109/build/three.module.js';
		import * as DAT from 'https://cdn.jsdelivr.net/npm/dat.gui@0.7.7/build/dat.gui.module.js';

		import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three@0.109/examples/jsm/controls/OrbitControls.js';
		import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.109/examples/jsm/loaders/GLTFLoader.js';

		import { createConvexRegionHelper } from '../common/js/NavMeshHelper.js';
		import { createCellSpaceHelper } from '../common/js/CellSpacePartitioningHelper.js';
		import { CustomVehicle } from './src/CustomVehicle.js';
		import { PathPlanner } from './src/PathPlanner.js';

		let renderer, scene, camera;

		let entityManager, time, pathPlanner, vehicleMesh;

		const vehicleCount = 100;
		const vehicles = [];
		const pathHelpers = [];

		const params = {
			showNavigationPaths: false,
			showRegions: false,
			showSpatialIndex: false,
		};

		let spatialIndexHelper;
		let regionHelper;

		init();

		function init() {

			scene = new THREE.Scene();

			camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 1000 );
			camera.position.set( 60, 40, 60 );
			camera.lookAt( scene.position );

			//

			const pathMaterial = new THREE.LineBasicMaterial( { color: 0xff0000 } );

			//

			const vehicleGeometry = new THREE.ConeBufferGeometry( 0.1, 0.5, 16 );
			vehicleGeometry.rotateX( Math.PI * 0.5 );
			vehicleGeometry.translate( 0, 0.1, 0 );
			const vehicleMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000 } );

			const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.6 );
			hemiLight.position.set( 0, 100, 0 );
			scene.add( hemiLight );

			const dirLight = new THREE.DirectionalLight( 0xffffff, 0.8 );
			dirLight.position.set( 0, 200, 100 );
			scene.add( dirLight );

			// renderer

			renderer = new THREE.WebGLRenderer( { antialias: true } );
			renderer.setSize( window.innerWidth, window.innerHeight );
			renderer.gammaOutput = true;
			document.body.appendChild( renderer.domElement );

			// dat.gui

			const gui = new DAT.GUI( { width: 400 } );

			gui.add( params, 'showNavigationPaths', 1, 30 ).name( 'show navigation paths' ).onChange( ( value ) => {

				for ( let i = 0, l = pathHelpers.length; i < l; i ++ ) {

					pathHelpers[ i ].visible = value;

				}

			} );

			gui.add( params, 'showRegions', 1, 30 ).name( 'show regions' ).onChange( ( value ) => {

				regionHelper.visible = value;

			} );

			gui.add( params, 'showSpatialIndex', 1, 30 ).name( 'show spatial index' ).onChange( ( value ) => {

				spatialIndexHelper.visible = value;

			} );

			gui.open();

			const controls = new OrbitControls( camera, renderer.domElement );
			controls.minDistance = 10;
			controls.maxDistance = 200;

			//

			window.addEventListener( 'resize', onWindowResize, false );

			const loadingManager = new THREE.LoadingManager( () => {

				// 3D assets are loaded, now load nav mesh

				const loader = new YUKA.NavMeshLoader();
				loader.load( '../common/navmeshes/complex/navmesh.glb' ).then( ( navigationMesh ) => {

					// visualize convex regions

					regionHelper = createConvexRegionHelper( navigationMesh );
					regionHelper.visible = false;
					scene.add( regionHelper );


					entityManager = new YUKA.EntityManager();
					time = new YUKA.Time();

					pathPlanner = new PathPlanner( navigationMesh );

					// setup spatial index

					const width = 100, height = 40, depth = 75;
					const cellsX = 20, cellsY = 5, cellsZ = 20;

					navigationMesh.spatialIndex = new YUKA.CellSpacePartitioning( width, height, depth, cellsX, cellsY, cellsZ );
					navigationMesh.updateSpatialIndex();

					spatialIndexHelper = createCellSpaceHelper( navigationMesh.spatialIndex );
					scene.add( spatialIndexHelper );
					spatialIndexHelper.visible = false;

					// create vehicles

					vehicleMesh = new THREE.InstancedMesh( vehicleGeometry, vehicleMaterial, vehicleCount );
					vehicleMesh.frustumCulled = false;
					scene.add( vehicleMesh );

					for ( let i = 0; i < vehicleCount; i ++ ) {

						// path helper

						const pathHelper = new THREE.Line( new THREE.BufferGeometry(), pathMaterial );
						pathHelper.visible = false;
						scene.add( pathHelper );
						pathHelpers.push( pathHelper );

						// vehicle

						const vehicle = new CustomVehicle();
						vehicle.navMesh = navigationMesh;
						vehicle.maxSpeed = 1.5;
						vehicle.maxForce = 10;

						const toRegion = vehicle.navMesh.getRandomRegion();
						vehicle.position.copy( toRegion.centroid );
						vehicle.toRegion = toRegion;

						const followPathBehavior = new YUKA.FollowPathBehavior();
						followPathBehavior.nextWaypointDistance = 0.5;
						followPathBehavior.active = false;
						vehicle.steering.add( followPathBehavior );

						entityManager.add( vehicle );
						vehicles.push( vehicle );

					}

					// update UI

					const entityCount = document.getElementById( 'entityCount' );
					entityCount.textContent = vehicleCount;

					const regionCount = document.getElementById( 'regionCount' );
					regionCount.textContent = navigationMesh.regions.length;

					const partitionCount = document.getElementById( 'partitionCount' );
					partitionCount.textContent = navigationMesh.spatialIndex.cells.length;

					const loadingScreen = document.getElementById( 'loading-screen' );

					loadingScreen.classList.add( 'fade-out' );
					loadingScreen.addEventListener( 'transitionend', onTransitionEnd );

					//

					animate();

				} );

			} );

			//

			const glTFLoader = new GLTFLoader( loadingManager );
			glTFLoader.load( 'model/level.glb', ( gltf ) => {

				// add object to scene

				scene.add( gltf.scene );
				gltf.scene.rotation.y = Math.PI;

			} );

		}

		function onPathFound( vehicle, path ) {

			// update path helper

			const index = vehicles.indexOf( vehicle );
			const pathHelper = pathHelpers[ index ];

			pathHelper.geometry.dispose();
			pathHelper.geometry = new THREE.BufferGeometry().setFromPoints( path );

			// update path and steering

			const followPathBehavior = vehicle.steering.behaviors[ 0 ];
			followPathBehavior.active = true;
			followPathBehavior.path.clear();

			for ( const point of path ) {

				followPathBehavior.path.add( point );

			}

		}

		function onWindowResize() {

			camera.aspect = window.innerWidth / window.innerHeight;
			camera.updateProjectionMatrix();

			renderer.setSize( window.innerWidth, window.innerHeight );

		}

		function animate() {

			requestAnimationFrame( animate );

			updatePathfinding();

			const delta = time.update().getDelta();

			entityManager.update( delta );

			pathPlanner.update();

			updateInstancing();

			renderer.render( scene, camera );

		}

		function updatePathfinding() {

			for ( let i = 0, l = vehicles.length; i < l; i ++ ) {

				const vehicle = vehicles[ i ];

				if ( vehicle.currentRegion === vehicle.toRegion ) {

					vehicle.fromRegion = vehicle.toRegion;
					vehicle.toRegion = vehicle.navMesh.getRandomRegion();

					const from = vehicle.position;
					const to = vehicle.toRegion.centroid;

					pathPlanner.findPath( vehicle, from, to, onPathFound );

				}

			}

		}

		function updateInstancing() {

			for ( let i = 0, l = vehicles.length; i < l; i ++ ) {

				const vehicle = vehicles[ i ];

				vehicleMesh.setMatrixAt( i, vehicle.worldMatrix );

			}

			vehicleMesh.instanceMatrix.needsUpdate = true;

		}

		function onTransitionEnd( event ) {

			event.target.remove();

		}

	</script>

</body>
</html>
